﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ImTools;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using VisionApp.Startup.Models;

namespace VisionApp.Startup.ViewModels;

public partial class EditorWindowViewModel:ObservableObject
{
    //private string pluginsDirectory = Constants.BasePluginPath;
    [ObservableProperty]
    private ConfigModel _currentConfig;
    public ObservableCollection<ConfigFileModel> Configs { get; set; } = new();
    public ObservableCollection<ConfigItemViewModel> ConfigItems { get; set; } = new();
    [ObservableProperty]
    private ConfigFileModel _selectedConfigFile;
    private readonly ILogger<EditorWindowViewModel> logger;

    public EditorWindowViewModel(ILogger<EditorWindowViewModel> logger)
    {
        //var pluginFolders = Directory.GetDirectories(pluginsDirectory);
        //foreach (var pluginFolder in pluginFolders)
        //{
        //    var fileName = Path.Combine(pluginFolder, "pluginsettings.json");

        //    var cfg = LoadConfig(fileName);// 从Plugins文件夹加载所有DLL

        //    if (cfg == null) continue;
        //    var hasAdded= Configs.FindFirst(f=>f.PluginName == cfg.PluginName);
        //    if(hasAdded== null )
        //    {
        //        Configs.Add(cfg);
        //    }
        //}

        this.logger = logger;
    }
    partial void OnSelectedConfigFileChanged(ConfigFileModel? oldValue, ConfigFileModel newValue)
    {
        LoadConfig(newValue.FileFullName);
    }
    public ConfigFileModel LoadConfig(string fileName)
    {
        ConfigItems.Clear();
        var configFile=new ConfigFileModel();

        if (!File.Exists(fileName)) return null;

        configFile.FileFullName = fileName;

        var cfgStr=File.ReadAllText(fileName);
        if (cfgStr != null)
        {
            var cfg=JsonConvert.DeserializeObject<ConfigModel>(cfgStr);

            configFile.PluginName = cfg.PluginName;

            CurrentConfig = cfg;

            if (CurrentConfig.Data != null)
            {
                foreach (var kvp in CurrentConfig.Data)
                {
                    ConfigItems.Add(new ConfigItemViewModel(kvp.Key, kvp.Value));
                }
            }

            return configFile;
        }
        return null;
    }
    [RelayCommand(CanExecute = nameof(CanSaveOrEdit))]
    private void SaveConfig()
    {
        if (_currentConfig == null) return;

        try
        {
            _currentConfig.DataTime = DateTime.Now.ToString();
            _currentConfig.Data = ConfigItems.ToDictionary(item => item.Key, item => item.Value);
            string fullPath = SelectedConfigFile.FileFullName;
            string json = JsonConvert.SerializeObject(_currentConfig, Formatting.Indented);
            File.WriteAllText(fullPath, json);
            logger.LogInformation($"配置文件已成功保存！");
            MessageBox.Show($"配置文件已成功保存！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (System.Exception ex)
        {
            logger.LogError($"保存配置文件失败: {ex.Message}");
            MessageBox.Show($"保存配置文件失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
    private bool CanSaveOrEdit() => _currentConfig != null;
    [RelayCommand(CanExecute = nameof(CanSaveOrEdit))]
    private void AddNewItem()
    {
        ConfigItems.Add(new ConfigItemViewModel("NewKey", "NewValue"));
    }
    [RelayCommand(CanExecute = nameof(CanSaveOrEdit))]
    private void DeleteItem(ConfigItemViewModel item)
    {
        if (item != null)
        {
            ConfigItems.Remove(item);
        }
    }
}

public class ConfigFileModel
{
    public string FileFullName { get; set; }
    public string PluginName {  get; set; }
}
public class ConfigItemViewModel : ObservableObject
{
    private string _key;
    public string Key
    {
        get => _key;
        set { _key = value; OnPropertyChanged(); }
    }

    private object _value;
    public object Value
    {
        get => _value;
        set { _value = value; OnPropertyChanged(); }
    }

    public string ValueType => Value?.GetType().Name ?? "null";

    public ConfigItemViewModel(string key, object value)
    {
        Key = key;
        Value = value;
    }
}